<!--
 * @Description: 
 * @Author: qingyang
 * @Date: 2023-07-20 11:55:57
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-26 21:42:19
-->
<template>
  <CDialog
    :title="props.configNo ? '编辑填报配置' : '新建填报配置'"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    size="large"
  >
    <div class="edit-op-container" v-if="dialogVisible">
      <el-form ref="formRef" :model="taskForm" :rules="obj.rules" label-position="top">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="组织名称" prop="organizationCode">
              <el-input
                v-model:value="taskForm.organizationName"
                disabled
                v-if="!!props.configNo"
              ></el-input>
              <GSelectOrganization
                v-model:value="taskForm.organizationCode"
                @change="handleChangeSelectOrganization"
                isCurrent
                :clearable="false"
                v-else
              ></GSelectOrganization>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="taskForm.companyName" disabled placeholder="选择组织后自动带出" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发起人" prop="creator">
              <el-input v-model="taskForm.creator" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮箱" prop="creatorEmail">
              <el-input v-model="taskForm.creatorEmail" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <p class="g-font-14n1b g-mt16 g-mb16">填报配置详情</p>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="填报周期" prop="fillPeriod">
              <el-date-picker
                v-model="taskForm.fillPeriod"
                style="width: 100%"
                type="year"
                value-format="YYYY"
                placeholder="请选择周期"
                :disabled="!!props.configNo"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="填报频次" prop="fillFrequency">
              <el-radio-group v-model="taskForm.fillFrequency" :disabled="!!props.configNo">
                <el-radio label="MONTH">月</el-radio>
                <el-radio label="YEAR">年</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据填报组织" prop="fillOrganization">
              <el-tree-select
                :disabled="!taskForm.fillPeriod"
                @change="handleChangeOrg"
                ref="tree"
                v-model="taskForm.fillOrganization"
                :data="orgTreeData"
                multiple
                :render-after-expand="false"
                collapse-tags
                collapse-tags-tooltip
                show-checkbox
                filterable
                :props="treeSelectProps"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <CTable :data-source="dataSource" useDataSource :pagination="false" border>
        <vxe-column title="数据填报组织">
          <template #default="scope">
            {{ scope.row.organizationName }}
          </template>
        </vxe-column>
        <vxe-column title="关联监测计划">
          <template #default="scope">
            <CSelect
              @change="changeInventoryList(scope.row)"
              v-model="scope.row.inventoryNo"
              class="table-select"
              placeholder="请选择"
              filterable
              @visible-change="
                loadInventoryOptions($event, scope.row.organizationCode, taskForm.fillPeriod)
              "
            >
              <el-option
                v-for="item in inventoryOptions"
                :key="item.inventoryNo"
                :label="item.inventoryName"
                :value="item.inventoryNo"
              />
            </CSelect>
          </template>
        </vxe-column>
        <vxe-column title="数据审核人">
          <template #default="scope">
            <!-- <div>{{ scope.row.auditor }}</div> -->
            <CSelect
              @change="changeAudit(scope.row)"
              v-model="scope.row.auditorId"
              class="table-select"
              placeholder="请选择"
              filterable
              :filter-method="handleFilter"
              @visible-change="loadAuditorOptions($event, scope.row.organizationCode, scope.row)"
            >
              <el-option
                v-for="item in auditorOptions"
                :key="item.userId"
                :value="item.userId"
                :label="item.realName"
              >
                <COption :name="item.realName" :subName="item.email" />
              </el-option>
            </CSelect>
          </template>
        </vxe-column>
      </CTable>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
        :loading="loadingTS"
        v-if="props.configStatus !== configStatusTypeEnum.ON"
        @click="handleConfirm('SAVE')"
        >暂存</el-button
      >
      <el-button
        :loading="loadingAC"
        v-if="props.configStatus !== configStatusTypeEnum.OFF"
        type="primary"
        @click="handleConfirm('FINISH')"
        >完成</el-button
      >
    </template>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddOrEditTaskDialog'
};
</script>
<script lang="ts" setup>
import {
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  watch,
  reactive,
  nextTick,
  toRaw
} from 'vue';
import { CDialog } from '@/components/CDialog/index';
import { useMessage } from '@/hooks/useMessage';
import * as obj from './rules';
import { CTable } from '@/components/CTable/index';
import GSelectOrganization from '@/businessComponents/GSelectOrganization/index.vue';
import type { GSelectOrganizationOptionItem } from '@/businessComponents/GSelectOrganization/index.vue';
import {
  getConfigDetail,
  temporarySave,
  editConfig,
  createConfig,
  temporaryCreate,
  getEmissionListByOrgs
} from '@/apis/eci/dataManagement/config';
import { configStatusTypeEnum } from '@/constants/enum';
import { IFillOrganization } from '@/apis/eci/dataManagement/model/configModel';
import { getFillOrgTree } from '@/apis/common/common';
import { store } from '@/store';
import { useFillConfig } from './useFillConfig';
import { cloneDeep } from 'lodash';
import { CSelect } from '@/components/CSelect/index';
import { COption } from '@/components/COption/index';

interface SelectFillTypeDialogProps {
  visible: boolean;
  configNo: string;
  configStatus: '' | keyof typeof configStatusTypeEnum;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {});
const emit = defineEmits(['update:visible', 'refresh']);
const treeSelectProps = {
  label: 'organizationName'
};
const tree = ref();
const orgTreeData = ref<any[]>([]);
const dataSource = ref<IFillOrganization[]>([]);
const {
  auditorOptions,
  inventoryOptions,
  loadAuditorOptions,
  loadInventoryOptions,
  changeAudit,
  changeInventoryList,
  handleFilter
} = useFillConfig();
const dialogVisible = computed<boolean>({
  get: () => {
    console.log(props.visible);

    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (visible) {
      init();
      if (props.configNo) {
        getDetail();
      }
    } else {
      dataSource.value = [];
      orgTreeData.value = [];
      formRef.value?.resetFields();
    }
  }
);

const formRef = ref();
const loadingTS = ref(false);
const loadingAC = ref(false);
const { createMessage } = useMessage();
const taskForm = reactive({
  fillPeriod: '',
  configName: '',
  organizationCode: '',
  organizationName: '',
  companyName: '',
  creator: '',
  creatorEmail: '',
  fillFrequency: '',
  fillOrganization: [] as string[]
});
/**
 * 切换组织
 */

const handleChangeOrg = () => {
  nextTick(() => {
    if (taskForm.fillOrganization.length) {
      // 这里使用延时操作，确保dom完成渲染后才去调用getCheckedNodes
      setTimeout(async () => {
        const checkNode = tree.value.getCheckedNodes(true);
        try {
          const dataOrigin = toRaw(cloneDeep(dataSource.value));
          let result = await getEmissionListByOrgs(taskForm.fillOrganization, taskForm.fillPeriod);
          dataSource.value = checkNode.map((item: any) => {
            let index = dataOrigin.findIndex(n => item.organizationCode == n.organizationCode);
            //如果之前以前存在某一项之前返回dataOrigin[index]
            if (index > -1) {
              return dataOrigin[index];
            } else {
              return {
                organizationName: item.organizationName,
                organizationCode: item.organizationCode,
                inventoryNo: result[item.organizationCode]
                  ? result[item.organizationCode][0].inventoryName
                  : '',
                inventoryNoTemp: result[item.organizationCode]
                  ? result[item.organizationCode][0].inventoryNo
                  : '',
                inventoryName: result[item.organizationCode]
                  ? result[item.organizationCode][0]?.inventoryName
                  : '',
                auditor: item.userName,
                auditorId: item.userName,
                auditorIdTemp: item.userId,
                auditorEmail: item.email
              };
            }
          });
        } catch {
          dataSource.value = [];
        }
      }, 0);
    } else {
      dataSource.value = [];
    }
  });
};
function getDetail() {
  getConfigDetail(props.configNo).then(res => {
    taskForm.configName = res.configName;
    taskForm.fillPeriod = res.fillPeriod;
    taskForm.organizationCode = res.organizationCode;
    taskForm.organizationName = res.organizationName;
    taskForm.companyName = res.companyName;
    taskForm.fillFrequency = res.fillFrequency;
    getOrgTree();
    taskForm.fillOrganization = res.fillOrganizationInfo.map((val: IFillOrganization) => {
      return val.organizationCode;
    });
    const fillOrganizationInfo = res.fillOrganizationInfo.map((item: IFillOrganization) => {
      return {
        organizationName: item.organizationName,
        organizationCode: item.organizationCode,
        inventoryNo: item.inventoryName,
        inventoryNoTemp: item.inventoryNo,
        inventoryName: item.inventoryName,
        auditor: item.auditor,
        auditorId: item.auditor,
        auditorIdTemp: item.auditorId,
        auditorEmail: item.auditorEmail
      };
    });
    dataSource.value = fillOrganizationInfo;
  });
}

// 选择组织后 自动带出公司
function handleChangeSelectOrganization(value: string, option: GSelectOrganizationOptionItem) {
  taskForm.companyName = option?.item.companyName || '';
  taskForm.organizationName = option?.label || '';
  taskForm.fillOrganization = [];
  dataSource.value = [];
  getOrgTree();
}
/**
 * 获取组织树
 */
async function getOrgTree() {
  try {
    const res = await getFillOrgTree(
      'inventory_manager',
      taskForm.organizationCode || 'ORG1000001'
    );
    orgTreeData.value = res;
  } catch (error) {
    console.log('error', error);
    orgTreeData.value = [];
  }
}
function handleConfirm(type: 'SAVE' | 'FINISH') {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      console.log('dataSource.value', dataSource.value);
      let params = {
        configNo: props.configNo ? props.configNo : undefined,
        organizationCode: props.configNo ? undefined : taskForm.organizationCode,
        organizationName: props.configNo ? undefined : taskForm.organizationName,
        fillFrequency: props.configNo ? undefined : taskForm.fillFrequency,
        fillPeriod: props.configNo ? undefined : taskForm.fillPeriod,
        fillOrganizationInfo: dataSource.value.map(item => {
          return {
            organizationCode: item.organizationCode,
            organizationName: item.organizationName,
            inventoryNo: item.inventoryNoTemp ? item.inventoryNoTemp : item.inventoryNo,
            inventoryName: item.inventoryName,
            auditorId: item.auditorIdTemp ? item.auditorIdTemp : item.auditorId,
            auditor: item.auditor,
            auditorEmail: item.auditorEmail
          };
        })
      };
      console.log('dataSource-params', params);
      if (type == 'FINISH') {
        loadingAC.value = true;
        try {
          if (props.configNo) {
            await editConfig(params);
          } else {
            await createConfig(params);
          }
          createMessage.success(props.configNo ? '编辑成功！' : '新增成功！');
          dialogVisible.value = false;
          init();
          emit('refresh');
        } finally {
          loadingAC.value = false;
        }
      } else {
        loadingTS.value = true;
        try {
          if (props.configNo) {
            await temporarySave(params);
          } else {
            await temporaryCreate(params);
          }
          createMessage.success('暂存成功！');
          dialogVisible.value = false;
          init();
          emit('refresh');
        } finally {
          loadingTS.value = false;
        }
      }
    }
  });
}

function init() {
  taskForm.creatorEmail = store.state.user.userInfo.email;
  taskForm.creator = store.state.user.userInfo.realName;
}
</script>
<style lang="scss" scoped>
.edit-op-container {
  :deep(.vxe-body--row) {
    height: 36px;
  }
  :deep(.vxe-body--column) {
    position: relative;
    padding: 3px 0 !important;
    .el-select {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      .el-input__wrapper {
        height: 35px;
        border-radius: 0;
      }
    }
  }
}
</style>
